package com.xiegang.apipassenger.Service;

import com.xiegang.apipassenger.mapper.TencentMesMapper;
import com.xiegang.apipassenger.remote.ServicePassengerUserClient;
import com.xiegang.apipassenger.remote.ServiceVerificationClient;
import com.xiegang.internalcommon.constant.CommonStatusEnum;
import com.xiegang.internalcommon.constant.IdentityStants;
import com.xiegang.internalcommon.constant.TokenConstans;
import com.xiegang.internalcommon.dto.ResponseResult;
import com.xiegang.internalcommon.dto.TencentMes;
import com.xiegang.internalcommon.request.VerificationCodeDto;
import com.xiegang.internalcommon.response.NumberCodeResponse;
import com.xiegang.internalcommon.response.TokenResponse;
import com.xiegang.internalcommon.util.JWTUtil;
import com.xiegang.internalcommon.util.RedisPrefixUtils;
import com.xiegang.internalcommon.util.SendSmsUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author xieGang
 * @description
 * @date 2023/2/28 19:49
 **/
@Service
public class VerificationCodeService {

    @Autowired
    private ServiceVerificationClient serviceVerificationClient;

    @Autowired
    private ServicePassengerUserClient servicePassengerUserClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private TencentMesMapper tencentMesMapper;


    public ResponseResult verificationCode(String passengerPhone) {

        //调用验证码服务，获取验证码
        ResponseResult<NumberCodeResponse> numberCodeResponse = serviceVerificationClient.getNumberCode(6);
        int numberCode = numberCodeResponse.getData().getNumberCode();

        //存入redis  key value 过期时间 2分钟
        String key = RedisPrefixUtils.generateKeyByPassengerPhone(passengerPhone,IdentityStants.PASSENGER_IDENTITY);
        stringRedisTemplate.opsForValue().set(key,numberCode+"",2, TimeUnit.MINUTES);

        //调用短信运营商发送短信
        TencentMes tencentMes = SendSmsUtils.sendSms(passengerPhone, numberCode + "");
        if(tencentMes==null){
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),"调用短信接口返回数据为空！");
        }
        tencentMesMapper.insert(tencentMes);

        return ResponseResult.success();
    }


    public ResponseResult checkVerificationCode(String passengerPhone,String verificationCode){

        //根据手机号获取redis中的验证码
        String key = RedisPrefixUtils.generateKeyByPassengerPhone(passengerPhone,IdentityStants.PASSENGER_IDENTITY);
        String codeRedis = stringRedisTemplate.opsForValue().get(key);

        System.out.println("手机号："+passengerPhone+",读取到的验证码:"+codeRedis);
        //校验验证码
        if(StringUtils.isBlank(codeRedis) || StringUtils.isBlank(verificationCode) || !codeRedis.trim().equals(verificationCode.trim())){
            return ResponseResult.fail(CommonStatusEnum.VERIFICATIONCODEERROR.getCode(),CommonStatusEnum.VERIFICATIONCODEERROR.getMessage());
        }

        //判断是否存在，进行处理
        VerificationCodeDto verificationCodeDto = new VerificationCodeDto();
        verificationCodeDto.setPassengerPhone(passengerPhone);
        verificationCodeDto.setVerificationCode(verificationCode);
        servicePassengerUserClient.loginOrRegister(verificationCodeDto);
        //颁发令牌
        String accessToken = JWTUtil.generatorToken(passengerPhone, IdentityStants.PASSENGER_IDENTITY, TokenConstans.ACCESS_TOKEN_TYPE);
        String refreshToken = JWTUtil.generatorToken(passengerPhone, IdentityStants.PASSENGER_IDENTITY, TokenConstans.REFRESH_TOKEN_TYPE);
        // token 存入redis
        String accessTokenKey = RedisPrefixUtils.generateTokenKey(passengerPhone, IdentityStants.PASSENGER_IDENTITY,TokenConstans.ACCESS_TOKEN_TYPE);
        stringRedisTemplate.opsForValue().set(accessTokenKey,accessToken,30,TimeUnit.DAYS);

        String refreshTokenKey = RedisPrefixUtils.generateTokenKey(passengerPhone, IdentityStants.PASSENGER_IDENTITY,TokenConstans.REFRESH_TOKEN_TYPE);
        stringRedisTemplate.opsForValue().set(refreshTokenKey,refreshToken,31,TimeUnit.DAYS);


        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(accessToken);
        tokenResponse.setRefreshToken(refreshToken);

        return ResponseResult.success(tokenResponse);
    }
}
